package com.titleevaluation.service;

import com.titleevaluation.entity.AcademicOrganizations;
import com.titleevaluation.entity.Application;
import com.titleevaluation.repository.AcademicOrganizationsRepository;
import com.titleevaluation.repository.ApplicationRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class AcademicOrganizationsService {

    private final AcademicOrganizationsRepository academicOrganizationsRepository;
    private final ApplicationRepository applicationRepository;

    public AcademicOrganizationsService(AcademicOrganizationsRepository academicOrganizationsRepository, ApplicationRepository applicationRepository) {
        this.academicOrganizationsRepository = academicOrganizationsRepository;
        this.applicationRepository = applicationRepository;
    }

    public AcademicOrganizations createAcademicOrganizations(Long applicationId, AcademicOrganizations academicOrganizations) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        academicOrganizations.setApplication(application);
        academicOrganizations.setCreatedAt(LocalDateTime.now());
        academicOrganizations.setUpdatedAt(LocalDateTime.now());
        return academicOrganizationsRepository.save(academicOrganizations);
    }

    public List<AcademicOrganizations> getAcademicOrganizationsByApplicationId(Long applicationId) {
        return academicOrganizationsRepository.findByApplicationId(applicationId);
    }

    public Optional<AcademicOrganizations> getAcademicOrganizationsById(Long id) {
        return academicOrganizationsRepository.findById(id);
    }

    public AcademicOrganizations updateAcademicOrganizations(Long id, AcademicOrganizations updatedAcademicOrganizations) {
        AcademicOrganizations existingAcademicOrganizations = academicOrganizationsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("AcademicOrganizations not found"));

        existingAcademicOrganizations.setOrganizationName(updatedAcademicOrganizations.getOrganizationName());
        existingAcademicOrganizations.setPosition(updatedAcademicOrganizations.getPosition());
        existingAcademicOrganizations.setStartDate(updatedAcademicOrganizations.getStartDate());
        existingAcademicOrganizations.setEndDate(updatedAcademicOrganizations.getEndDate());
        existingAcademicOrganizations.setRemarks(updatedAcademicOrganizations.getRemarks());
        existingAcademicOrganizations.setUpdatedAt(LocalDateTime.now());

        return academicOrganizationsRepository.save(existingAcademicOrganizations);
    }

    public void deleteAcademicOrganizations(Long id) {
        academicOrganizationsRepository.deleteById(id);
    }
}

